import { Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';

export class TypeormConfigService implements TypeOrmOptionsFactory {
  constructor(@Inject(REQUEST) private request: Request) {}

  createTypeOrmOptions(
    connectionName?: string,
  ): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
    const headers = this.request.headers;
    const tenantId = headers['x-tenant-id'] as string | undefined;

    let config: Partial<TypeOrmModuleOptions> = {
      port: 3306,
    };
    if (tenantId === 'mysql') {
      config = {
        type: 'mysql' as const,
        port: 3306,
      };
    } else if (tenantId === 'postgres') {
      config = {
        type: 'postgres' as const,
        port: 5432,
        username: 'pguser',
        database: 'testdb',
      };
    }

    const envConfig = {
      type: 'mysql' as const,
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'testdb',
      synchronize: true,
      autoLoadEntities: true,
    };
    const finalConfig = { ...envConfig, ...config };
    return finalConfig as TypeOrmModuleOptions;
  }
}
